//
//  PeopleNearViewController.m
//  HotWord
//
//  Created by Ji Qi on 12-6-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PeopleNearViewController.h"
#import "PeopleDreamSchoolViewController.h"
#import "UserInfoViewController.h"
#import "Match.h"
#import "SliderBtn.h"

@implementation PeopleNearViewController
@synthesize photoCardTableView;
@synthesize backBtn;
@synthesize sortTypeView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.photoCardTableView.top = self.view.height;
    _noMore = YES;
    
    if (_hasNoFilter && !_hasGREMajor)
    {
        self.universityBtn.hidden = YES;
    }
    
    SliderBtn *sliderBtn = (SliderBtn *)[[[NSBundle mainBundle] loadNibNamed:@"SliderBtn" owner:self options:nil] objectAtIndex:0];
    sliderBtn.tag = 111;
    [self.view addSubview:sliderBtn];
    
    self.photoCardTableView.tableHeaderView = self.headerView;
    
    self.headerTitleLabel.text = @"ALL";

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!_haveLoaded) {
        _haveLoaded = YES;
        [self request];
    }
}

- (void)request
{
    [[UserManager sharedManager].nearByUsers removeAllObjects];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    }
    [params setObject:@"1" forKey:@"pageNo"];
    [params setObject:@"10" forKey:@"pageSize"];
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeListUser WithParameters:params AndCallBackScope:self AndSuccessSel:@"getUserSuccess:" AndFailedSel:@"getUserFailed:"];
    if ([[UserManager sharedManager].nearByUsers count] <= 0) {
        [[HTActivityIndicator currentIndicator] displayActivity:@"Searching..."];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[HTActivityIndicator currentIndicator] hide];
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![APP_DELEGATE.touchMaskView isDescendantOfView:self.view])
    {
        [self.view insertSubview:APP_DELEGATE.touchMaskView belowSubview:[self.view viewWithTag:111]];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == [[UserManager sharedManager].nearByUsers count]){// && !_noMore) {
        UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (_loadingMore) {
            UIActivityIndicatorView	*activiter = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
            activiter.center = cell.center;
            activiter.left = 100;
            [activiter startAnimating];
            [cell addSubview:activiter];
            cell.textLabel.text = @"Loading...";
        }
        else
        {
            cell.textLabel.text = @"MORE";
        }
        return cell;
    }
    else {
        
        static NSString *CellIdentifier = @"NearUserInfoCell";
        
        NearUserInfoCell *cell = (NearUserInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NearUserInfoCell" owner:self options:nil] objectAtIndex:0];
        }
        
        User *user = [[UserManager sharedManager].nearByUsers objectAtIndex:indexPath.row];
        [cell setUserForCell:user];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == [[UserManager sharedManager].nearByUsers count]) {
        return 40;
    }
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_noMore || [[UserManager sharedManager].nearByUsers count] == 0) {
        return [[UserManager sharedManager].nearByUsers count];
    }
    return [[UserManager sharedManager].nearByUsers count] + 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [[UserManager sharedManager].nearByUsers count]) {
        [self loadMore];
    }
    else {
        
        User *user = [[UserManager sharedManager].nearByUsers objectAtIndex:indexPath.row];
//        FriendInfoViewController *friendInfoViewController = [[[FriendInfoViewController alloc] initWithUser:user] autorelease];
//        [self.navigationController pushViewController:friendInfoViewController animated:YES];
        UserInfoViewController *userInfoViewController = [[[UserInfoViewController alloc] initWithUser:user] autorelease];
        [self.navigationController pushViewController:userInfoViewController animated:YES];

    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
	if (_loadingMore || _noMore) {
		return;
	}
	CGPoint origin = scrollView.bounds.origin;
	if (scrollView.contentSize.height - origin.y <= self.view.bounds.size.height - 40) {
		[self loadMore];
	}
}

- (void)loadMore
{
    _loadingMore = YES;
    NSInteger userCount = [[UserManager sharedManager].nearByUsers count];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    }
    [params setObject:[NSString stringWithFormat:@"%d", userCount/10 + 1] forKey:@"pageNo"];
    [params setObject:@"10" forKey:@"pageSize"];
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeListUser WithParameters:params AndCallBackScope:self AndSuccessSel:@"getUserSuccess:" AndFailedSel:@"getUserFailed:"];
    [self.photoCardTableView reloadData];
}

- (void)viewDidUnload
{
    [self setPhotoCardTableView:nil];
    [self setBackBtn:nil];
    [self setSortTypeView:nil];
    [self setAdView:nil];
    [self setAdImageView:nil];
    [self setAdTtileLabel:nil];
    [self setAdDescLabel:nil];
    [self setAdLoadingIndicatorView:nil];
    [self setAdBtn:nil];
    [self setAdContainerView:nil];
    [self setUniversityBtn:nil];
    [self setNullDataImageView:nil];
    [self setRefreshBtn:nil];
    [self setHeaderView:nil];
    [self setHeaderTitleLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (IBAction)tapOnRefreshBtn:(id)sender {
    [self request];
}

- (IBAction)tapOnBackBtn:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapOnUniversity:(id)sender {
//    NSString *message = nil;
//    
//    if (IS_STRING_EMPTY([UserManager sharedManager].currentUser.match.matchType) || [@"0" isEqualToString:[UserManager sharedManager].currentUser.match.matchType])
//    {
//        message = @"Please Make A Choice in \"I'M LOOKING FOR\"!";
//        [self showAlertViewWithMessage:message];
//        return;
//    }
//    
//    if (IS_STRING_EMPTY([UserManager sharedManager].currentUser.exam))
//    {
//        message = @"Please Make A Choice in \"test\"!";
//        [self showAlertViewWithMessage:message];
//        return;
//    }

    
//    [UIView beginAnimations:nil context:nil];
//	[UIView setAnimationDuration:0.5f];
//	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//	[UIView setAnimationRepeatAutoreverses:NO];
//	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[UIApplication sharedApplication].keyWindow cache:NO];
//    [self.navigationController popViewControllerAnimated:NO];
//    [UIView commitAnimations];
    
    UIActionSheet *actionSheet = nil;
    User *currentUser =[UserManager sharedManager].currentUser;
    if ([@"GRE" isEqualToString:currentUser.exam])
    {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"Explore" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"全部（ALL）", @"兴趣（Looking For）", @"专业（Major）",nil];
    }
    else
    {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"Explore" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"全部（ALL）", @"兴趣（Looking For）",nil];
    }
    
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.view];
    [actionSheet release];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    
    User *currentUser =[UserManager sharedManager].currentUser;
    UIViewController *viewController = nil;
    switch (buttonIndex)
    {
        case 0:
        {
            return;
        }
            break;
        case 1:
        {
            if (IS_STRING_EMPTY(currentUser.match.matchType) || [@"0" isEqualToString:currentUser.match.matchType])
            {
                [self showAlertViewWithMessage:@"Please Make A Choice in \"I'M LOOKING FOR\"!"];
                return;
            }

            PeopleDreamSchoolViewController * peopleDreamSchoolViewController = [[[PeopleDreamSchoolViewController alloc] init] autorelease];
            viewController = peopleDreamSchoolViewController;

        }
            break;
        case 2:
            {
                if (IS_STRING_EMPTY(currentUser.major))
                {
                    [self showAlertViewWithMessage:@"Please Make A Choice in \"Major\"!"];
                    return;
                }
                
                PeopleDreamSchoolViewController * peopleDreamSchoolViewController = [[[PeopleDreamSchoolViewController alloc] init] autorelease];
                peopleDreamSchoolViewController.isListByGREMajor = YES;
                viewController = peopleDreamSchoolViewController;
            }
            break;
        default:
            break;
    }
    
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    UINavigationController *navController = (UINavigationController *)APP_DELEGATE.window.rootViewController;
    [navController pushViewController:viewController animated:NO];
    
    [UIView commitAnimations];
}


- (void)showAlertViewWithMessage:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
    [alertView show];
    [alertView release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)getUserSuccess:(NSObject *)result
{
    if (![result isKindOfClass:[NSDictionary class]]) {
        [self requestHandle];

        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        NSArray *userDics = [dic objectForKey:@"data"];
        for (NSDictionary *userDic in userDics) {
            User *user = [[[User alloc] init] autorelease];
            user.userId = [UtilHelper getStringValue:[userDic objectForKey:@"id"]];
            user.email = [UtilHelper getStringValue:[userDic objectForKey:@"email"]];
            user.nickname = [UtilHelper getStringValue:[userDic objectForKey:@"nick"]];
            user.gender = [UtilHelper getStringValue:[userDic objectForKey:@"gender"]];
            if ([@"F" isEqualToString:user.gender]) {
                user.gender = @"Girl";
            }
            else if ([@"M" isEqualToString:user.gender]) {
                user.gender = @"Boy";
            }
            user.exam = [UtilHelper getStringValue:[userDic objectForKey:@"exam"]];
            
            NSInteger examType = [user.exam integerValue];
            if (IS_STRING_NOT_EMPTY(user.exam) && examType <= 6 && examType >= 0)
            {
                user.exam = [EXAM_ARRAY objectAtIndex:examType];
            }
            else
            {
                user.exam = @"";
            }
            
            BOOL isTeacher = [[UtilHelper getStringValue:[userDic objectForKey:@"isteacher"]] boolValue];
            if (isTeacher)
            {
                user.identity = @"Teacher";
            }
            else
            {
                user.identity = @"Student";
            }
            
            user.applyYear = [UtilHelper getStringValue:[userDic objectForKey:@"applyYear"]];
            user.testSection = [UtilHelper getStringValue:[userDic objectForKey:@"section"]];
            user.major = [UtilHelper getStringValue:[userDic objectForKey:@"major"]];
            
            Match *match = [[Match alloc] init];
            match.matchType = [UtilHelper getStringValue:[userDic objectForKey:@"filterType"]];
            match.dreamschool = [UtilHelper getStringValue:[userDic objectForKey:@"dreamschoolName"]];
            match.examYear = [UtilHelper getStringValue:[userDic objectForKey:@"examYear"]];
            match.examMonth = [UtilHelper getStringValue:[userDic objectForKey:@"examMonth"]];
            match.examAddress = [UtilHelper getStringValue:[userDic objectForKey:@"examAddress"]];
            user.match = match;
            [match release];
            
            user.avater = [UtilHelper getStringValue:[userDic objectForKey:@"avater"]];
            user.avater1 = [UtilHelper getStringValue:[userDic objectForKey:@"avater1"]];
            user.avater2 = [UtilHelper getStringValue:[userDic objectForKey:@"avater2"]];
            user.lastLogin = [UtilHelper getStringValue:[userDic objectForKey:@"lastLogin"]];
            user.lastMsg = [UtilHelper getStringValue:[userDic objectForKey:@"lastMsg"]];
            user.longitude = [UtilHelper getStringValue:[userDic objectForKey:@"longitude"]];
            user.latitude = [UtilHelper getStringValue:[userDic objectForKey:@"latitude"]];
            user.year = [UtilHelper getStringValue:[userDic objectForKey:@"year"]];
            user.dreamSchool = [UtilHelper getStringValue:[userDic objectForKey:@"dreamSchool"]];
            user.dreamSchoolCN = [UtilHelper getStringValue:[userDic objectForKey:@"dreamSchoolCn"]];
            user.dreamSchoolEN = [UtilHelper getStringValue:[userDic objectForKey:@"dreamSchoolEn"]];
            user.country = [UtilHelper getStringValue:[userDic objectForKey:@"country"]];
            user.city = [UtilHelper getStringValue:[userDic objectForKey:@"city"]];
            user.status = [UtilHelper getStringValue:[userDic objectForKey:@"status"]];
            user.distance = [UtilHelper getStringValue:[userDic objectForKey:@"distance"]];
            [[UserManager sharedManager].nearByUsers addObject:user];
            [[UserManager sharedManager].cacheUsers addObject:user];
            
        }
        
        if ([userDics count] < 10) {
            _noMore = YES;
        }
        else {
            _noMore = NO;
        }
        [[HTActivityIndicator currentIndicator] hide];
        
    }
    else {
        if (!_loadingMore) {
            [[HTActivityIndicator currentIndicator] displayMessage:@"Searching Failed!"];
        }
    }
    
    [self requestHandle];
    
    _loadingMore = NO;
    [self.photoCardTableView reloadData];
}

- (void)requestHandle
{
    _nullDataImageView.hidden = YES;
    _refreshBtn.hidden = YES;
    if ([[UserManager sharedManager].nearByUsers count] == 0)
    {
        _nullDataImageView.hidden = NO;
        _refreshBtn.hidden = NO;
    }
    else
    {
        if (!_loadingMore)
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.photoCardTableView.top = 0;
            }];
        }
    } 
}

- (void)getUserFailed:(NSObject *)result
{
    if (!_loadingMore) {
        
        [[HTActivityIndicator currentIndicator] displayMessage:@"Searching Failed!"];
    }
    [self requestHandle];

    _loadingMore = NO;
    [self.photoCardTableView reloadData];
    
}

- (void)dealloc {
    [photoCardTableView release];
    [backBtn release];
    [sortTypeView release];
    [_adView release];
    [_adImageView release];
    [_adTtileLabel release];
    [_adDescLabel release];
    [_adLoadingIndicatorView release];
    [_adBtn release];
    [_adContainerView release];
    [_universityBtn release];
    [_nullDataImageView release];
    [_refreshBtn release];
    [_headerView release];
    [_headerTitleLabel release];
    [super dealloc];
}
@end
